#include "hqlabel.h"

HqLabel::HqLabel()
{
    this->setAlignment(Qt::AlignCenter);
    this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    hq_movie = NULL;
    m_movie = NULL;
    m_grab_flag = false;

    m_layout = NULL;
    m_animation = NULL;

    m_url = "";

    m_rolling_text = "";

    m_qss1 = "";
    m_qss2 = "";
    m_place_way = "PH";
    m_format = "";
    m_animation_int = None;

    connect(&m_timer, SIGNAL(timeout()), this, SLOT(UpdateIndex()));
}

HqLabel::~HqLabel()
{
    if (m_layout != NULL)
    {
        delete m_layout;
        m_layout = NULL;
    }

    if (m_animation != NULL)
    {
        delete m_animation;
        m_animation = NULL;
    }

    if (m_timer.isActive())
    {
        m_rolling_text = "";
        m_timer.stop();
    }
}
void HqLabel::StartHqv()
{
    if (hq_movie != NULL)
        hq_movie->start();
}

void HqLabel::CleanHqv()
{
    // 解决设置gif或者png图片之前设置过hqv资源，清除一下
    if (NULL != hq_movie)
    {
        hq_movie->stop();
        hq_movie->setLabel(NULL);
    }
}

//每个控件都会使用这个paintevent
void HqLabel::paintEvent(QPaintEvent *event)
{
    //保证其他控件正常显示
    if (m_rolling_text == "")
    {
        QLabel::paintEvent(event);
        return;
    }

    QPainter painter(this);
    painter.setRenderHint(QPainter::TextAntialiasing);

    //drawText传入的参数为文字位置时，该位置是文字的左下角。我们使用(视口的高度 - 文字高度)/2 + 文字高度使文字垂直方向居中显示。
    painter.drawText(m_pos_x, (height()-m_text_height)/2 + m_text_height, m_rolling_text);
}

void HqLabel::UpdateIndex()
{
    update();

    m_pos_x -= 1;

    if (m_pos_x < 0 && abs(m_pos_x) >= m_text_width)
        m_pos_x = width();
}

void HqLabel::StartScrollText(QString qss)
{
    //只支持单行hqt
    if (!m_url.contains(".hqt") || m_url.contains("@@"))
        return;

    if (!m_url.contains("##"))
        return;

    QStringList list = m_url.split("##");
    QString text_with_suffix = list.at(1);
    QString rolling_text = text_with_suffix.left(text_with_suffix.size() - 4);
    QString rolling_content = myapp::getQssContentByKey(qss, "rolling");
    if (rolling_content != "")
    {
        int ms_per_px = rolling_content.toInt();
        if (ms_per_px == 0)
            ms_per_px = DEFAULT_MS_PER_PX;
        QString font_size = myapp::getQssContentByKey(qss, "font-size");
        int size = font_size.left(font_size.size()-2).toInt();
        QFont font;
        font.setPointSize(size);
        QFontMetrics fontMetrics(font);
        m_text_width = fontMetrics.width(rolling_text);
        m_rolling_text = rolling_text;
        m_text_height = fontMetrics.height();
        m_pos_x = 0;

        m_timer.start(ms_per_px);
    }
}

void HqLabel::ClearChild()
{
    QList<QWidget*> items = this->findChildren<QWidget*>();

    foreach (QWidget *item, items)
    {
        item->setParent(NULL);
        item->deleteLater();
    }
}

//文本截屏并设置图片
void HqLabel::SetGrabPixmap()
{
    QPixmap p = this->grab();

//    QString filePathName = "widget";
//    filePathName += ".png";
//    p.save(filePathName, "png");

    ClearChild();
    setPixmap(p);
    setScaledContents(true);
}

//文本+旋转+动画需要截屏，截屏需要在show之后，此函数专门用来进行show之后在此播放动画
void HqLabel::ReRunHqtRotateGrabAnimation(Animation animation)
{
    if (m_animation != NULL)
    {
        delete m_animation;
        m_animation = NULL;
    }
    m_animation = new MyAnimation(this);
    m_animation->ReRunHqtRotateGrabAnimation(animation);
}

//获取格式化字符串中参数的个数
QList<int> HqLabel::GetFormatParaNum(const QString &format)
{
    QList<int> para_list;

    //默认只支持少于十个参数
    for (int i = 1; i<10; i++)
    {
        if (format.contains(QString("%") + QString::number(i)))
        {
            para_list.push_back(i);
        }
    }

    return para_list;
}

void HqLabel::RunHqtStyle(QString text, QString qss1, QString qss2, QString place_way, Animation animation, QString format)
{
    LOG_QDEBUG << "text:" << text;
    LOG_QDEBUG << "qss1:" << qss1;
    LOG_QDEBUG << "qss2:" << qss2;
    LOG_QDEBUG << "place_way:" << place_way;
    LOG_QDEBUG << "animation:" << animation;
    LOG_QDEBUG << "format:" << format;


    if (format != "")
    {
        //获取格式化参数的个数
        QList<int> para_list = GetFormatParaNum(format);
        if (para_list.size() != 0)
        {
            //获取实参个数
            QStringList list = text.split("@@");

            for (int i = 0; i < para_list.size(); i++)
            {
                //替换参数
                QString para = QString("%") + QString::number(para_list.at(i));
                text = format.replace(para, list.at(para_list.at(i)-1));
            }
        }
    }
    //先把原有的动画停止
    if (m_animation != NULL)
        m_animation->RestoreAnimation();

    if (m_animation_int != animation)
    {
        //先清除前面残留的动画效果截图
        clear();
        //之后删除m_layout，因为要重新创建m_layout之前的由于动画原因需要截图m_layout的子控件都删了,需要重新绘制m_layout
        if (m_layout != NULL)
        {
            delete m_layout;
            m_layout = NULL;
        }
    }
    //工厂创建排列方式生成layout
    if (m_layout == NULL)
    {
        CreatePlaceWayLayout place_way_factory;
        m_layout = place_way_factory.CreateLayout(place_way);
        if (m_layout == NULL)
            return;
        //在this上设置layout
        m_layout->SetWidget(this, text, qss1, qss2);
    } else
    {
        //不销毁只是重新设置参数
        m_layout->SetParam(text, qss1, qss2);
    }
    if (m_animation == NULL)
        m_animation = new MyAnimation(this);
    m_animation->RunHqtAnimation(place_way, animation);
    m_qss1 = qss1;
    m_qss2 = qss2;
    m_format = format;
    m_place_way = place_way;
    m_animation_int = animation;
}

//hqt支持动态切换样式
void HqLabel::ReLoadUrl(QString prefix, QString url)
{
    LOG_QDEBUG << "reload prefix:" << prefix << "  reload url:" << url;
    if (url.contains(".png"))
    {
        //重新显示如果之前是动图要先销毁
        if (NULL != m_movie)
        {
            m_movie->stop();
            delete m_movie;
            m_movie = NULL;
        }

        if (hq_movie != NULL)
        {
            hq_movie->stop();
            delete hq_movie;
            hq_movie = NULL;
        }

        url.push_front(prefix);
        clear();
        QPixmap pixmap(url);
        setPixmap(pixmap);
        setScaledContents(true);
    } else if (url.contains(".hqv"))
    {
        SetHqvCnt(prefix, url);

    } else if (url.contains(".gif"))
    {
        SetGifCnt(prefix, url);
    } else if (url.contains(".hqt"))
    {
        //不支持重新加载样式
        if (url.contains("##"))
            return;
        m_layout->ResetHqtext(url.left(url.size() - 4));
    }
}

void HqLabel::RunPngStyle(QString url, Animation animation)
{
    //LOG_QDEBUG << "url:" << url;
    //LOG_QDEBUG << "animation:" << animation << endl;

    //跑之前先清除label，否则重新显示可能有残留
    clear();

    QPixmap pixmap(url);
    setPixmap(pixmap);
    setScaledContents(true);

    if (m_animation != NULL)
    {
        delete m_animation;
        m_animation = NULL;
    }

    if (m_animation == NULL)
        m_animation = new MyAnimation(this);

    m_animation->RunPngAnimation(animation);

    m_animation_int = animation;
}


void HqLabel::SetHqvCnt(QString prefix, QString url)
{
    url.push_front(prefix);
    if (hq_movie == NULL)
    {
        hq_movie = new HuaqiMovie(this);
        if (NULL == hq_movie)
            return;
    }
    else
    {
        hq_movie->stop();
    }

    hq_movie->setFileName(url);
    QStringList list = hq_movie->getImageList();
    if (list.count() < 0)
        return;

    hq_movie->setLabel(this);
    hq_movie->showOne();
}

void HqLabel::SetGifCnt(QString prefix, QString url)
{
    url.push_front(prefix);
    if (NULL == m_movie)
    {
        m_movie = new QMovie(url, QByteArray(), this);
        if (NULL == m_movie)
            return;
    }
    else
    {
        m_movie->stop();
    }
    m_movie->setFileName(url);
    m_movie->start();
    m_movie->setScaledSize(size());
    setMovie(m_movie);
}

void HqLabel::SetPngCnt(QString prefix, QString animation_url)
{
    if (animation_url.contains("##"))
    {
        QStringList list = animation_url.split("##");
        QString url = list.at(1);
        url.push_front(prefix);
        if (list.at(0) == "")
        {
            RunPngStyle(url);
            return;
        }
        QString filename = prefix + QString(StyleConfigFile);
        QFileInfo fileInfo(filename);
        if (!fileInfo.isFile())
        {
            RunPngStyle(url);
            return;
        }
        QSettings settings(filename, QSettings::IniFormat);
        settings.setIniCodec(QTextCodec::codecForName("utf-8"));

        QStringList grp_list = settings.childGroups();
        if (grp_list.contains(list.at(0)))
        {
            settings.beginGroup(list.at(0));
            QString animation_str = settings.value("animation", "None").toString();
            settings.endGroup();
            Animation animation = None;
            if (animation_str == "LeftRight")
                animation = LeftRight;
            else if (animation_str == "OpacityEffect")
                animation = OpacityEffect;
            else if (animation_str == "Scale")
                animation = Scale;
            else if (animation_str == "TwoFrameScale")
                animation = TwoFrameScale;
            RunPngStyle(url, (Animation)animation);
        } else
        {
            RunPngStyle(url);
        }
    }
    else
    {
        animation_url.push_front(prefix);
        RunPngStyle(animation_url);
    }
}

void HqLabel::SetHqtCnt(QString prefix, QString text)
{
    setStyleSheet("background:transparent;");

    if (text.contains("##"))
    {
        QStringList list = text.split("##");
        QString name = list.at(1);
        if (list.at(0) == "")
        {
            RunHqtStyle(name);
            return;
        }
        QString filename = prefix + QString(StyleConfigFile);
        QFileInfo fileInfo(filename);
        if (!fileInfo.isFile())
        {
            RunHqtStyle(name);
            return;
        }

        QSettings settings(filename, QSettings::IniFormat);
        settings.setIniCodec(QTextCodec::codecForName("utf-8"));

        QStringList grp_list = settings.childGroups();

        QString css_group_name = "";

        if (grp_list.contains(list.at(0)))
        {
            css_group_name = list.at(0);
        } else
        {
            QStringList name_list = list.at(0).split("_");
            if (name_list.last().toInt() != 0)
            {
                int size = list.at(0).size();
                QString last = name_list.last();
                QString name = list.at(0).left(size - last.size() - 1);
                if (grp_list.contains(name))
                    css_group_name = name;
            }
        }

        if (css_group_name == "")
        {
            RunHqtStyle(name);
            return;
        }

        settings.beginGroup(css_group_name);
        QString qss1 = settings.value("qss1", "").toString();
        QString qss2 = settings.value("qss2", "").toString();
        QString format = settings.value("format", "").toString();
        QString place_way_str = settings.value("place_way", "PH").toString();
        QString animation_str = settings.value("animation", "None").toString();
        settings.endGroup();

        Animation animation = None;
        if (animation_str == "LeftRight")
            animation = LeftRight;
        else if (animation_str == "OpacityEffect")
            animation = OpacityEffect;
        else if (animation_str == "Scale")
            animation = Scale;
        else if (animation_str == "TwoFrameScale")
            animation = TwoFrameScale;

        RunHqtStyle(name, qss1, qss2, place_way_str, animation, format);

    } else
    {
        RunHqtStyle(text);
    }
}

QString HqLabel::GetUrl()
{
    return m_url;
}

void HqLabel::SetContent(QString prefix, QString url)
{
    /*
        name.gif
        name.hqv
        name.png
        name.hqt

        css_group##name.png
        css_group##name.hqt

        除此之外的直接显示不作处理
    */

    m_url = url;

    if ("hqv" == url.right(3))
    {
        SetHqvCnt(prefix, url);
    }
    else
    {
        // 解决设置gif或者png图片之前设置过hqv资源，清除一下
        CleanHqv();

        if ("gif" == url.right(3))
        {
            SetGifCnt(prefix, url);
        }
        else if ("png" == url.right(3))
        {
            SetPngCnt(prefix, url);
        }
        else if ("hqt" == url.right(3))
        {
            SetHqtCnt(prefix, url.left(url.size() - 4));
        } else
        {
            //如果url是空或者是其他类型的
            SetHqtCnt(prefix, url);
        }
    }
}
